<?php

namespace App\HttpController\Admin;

use App\Model\BacksModel;
use Carbon\Carbon;

/**
 * 背景图片管理
 * Class Backs
 * @package App\HttpController\Admin
 */
class Back extends Auth
{
    /**
     * 列表
     * @return bool|void
     * @throws \Throwable
     */
    public function index(){
        try{
            $request = $this->request();
            $page = $request->getRequestParam('page') ?? 1;
            $model = new BacksModel();
            $list = $model->select('id,img,created_at,title')->orderBy('created_at')->paginate($page);;
            return $this->writeJson(0,$list);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 全部
     * @return bool
     * @throws \Throwable
     */
    public function all(){
        try{
            $model = new BacksModel();
            $all = $model->select('id,title,img')->orderBy('created_at')->getAll();
            return $this->writeJson(0,$all);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

    /**
     * 更新
     * @return bool
     * @throws \Throwable
     */
    public function update(){
        try{
            $request = $this->request();
            $data = $request->getRequestParam();
            $model = new BacksModel();
            if($data['id']){
                //修改
                $model->update($data);
                return $this->writeJson(0,null,'编辑成功');
            }else{
                //新增
                $data['created_at'] = Carbon::now();
                $model->create($data);
                return $this->writeJson(0,null,'新增成功');
            }
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }

    }

    /**
     * 删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy(){
        try{
            $request = $this->request();
            $id = $request->getRequestParam('id') ?? 0;
            if(empty($id)){
                return $this->writeJson(1,null,'参数错误');
            }
            $model = new BacksModel();
            $model->destroy($id);
            return $this->writeJson(0);
        }catch (\Exception $e){
            return $this->writeJson(1,null,$e->getMessage());
        }
    }

}
